package com.xx.pmis.web.actions;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.xx.pmis.model.Present;
import com.xx.pmis.model.Shop;
import com.xx.pmis.model.util.PresentMonth;
import com.xx.pmis.services.PresentService;
import com.xx.pmis.services.ShopService;
import com.xx.pmis.web.forms.PresentForm;
import com.xx.pmis.web.util.AccountUtil;
import com.xx.pmis.web.util.CurrentDate;
import com.xx.pmis.web.util.PresentUtil;
import com.xx.pmis.web.util.Rand;

/**
 * @class 商品Action类 <br>
 * 
 * @editor 石星星 @Date 2011-9-21 下午03:17:42 <br>
 * @version jdk_1.5.0
 */
public class PresentAction extends PMISBaseAction {
	private static final Log log = LogFactory.getLog(PresentAction.class);

	PresentService presentService = getPMISServices().getPresentService();
	ShopService shopService = getPMISServices().getShopService();

	AccountUtil accountUtil = new AccountUtil();
	PresentUtil presentUtil = new PresentUtil();

	// 查询所有商品
	public ActionForward listPresent(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		List<Present> presentList = null;
		try {
			presentList = presentService.getAllPresentByCondition(" order by presentDate desc");
		} catch (Exception e) {
			String errorPage = "【物品管理/商品】查询【商品】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}
		request.setAttribute("presentList", presentList);
		return mapping.findForward("listPresent");
	}

	// 新增
	public ActionForward addPresent(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		List<?> shopList = null;
		try {
			shopList = shopService.getAllShopByShopType("1");
		} catch (Exception e) {
			String errorPage = "【物品管理/商品/新增】查询【商店】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}
		request.setAttribute("shopList", shopList);
		request.setAttribute("presentDate", CurrentDate.currentDate());
		request.setAttribute("position", "商品/新增");
		return mapping.findForward("addPresent");
	}

	// 新增，处理方法
	public ActionForward addPresent_Do(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		PresentForm f = (PresentForm) form;

		String presentName = f.getPresentName(); // 商品名称
		String presentType = f.getPresentType(); // 自用 0，送人 1
		String presentState = f.getPresentState(); // 想用 0，在用 1，用完 2
		String presentDate = f.getPresentDate(); // 购买日期，结算时作为流水账的记账日期
		String presentExpenses = f.getPresentExpenses(); // 费用
		String shopID = f.getShopID(); // 商店
		String presentDesc = f.getPresentDesc(); // 描述

		Present present = new Present();
		present.setPresentID(CurrentDate.currentYear() + Rand.getRand());
		present.setPresentName(presentName);
		present.setPresentType(presentType);
		present.setPresentState(presentState);
		present.setPresentDate(presentDate);
		present.setPresentExpenses(accountUtil.if1ZeroTo2Zero(presentExpenses));
		present.setShopID(shopID);
		present.setPresentDesc(presentDesc);
		present.setPresentPay("1");
		try {
			presentService.saveOrUpdatePresent(present);
		} catch (Exception e) {
			String errorPage = "【物品管理/商品/新增】保存或更新【商品】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}

		listPresentByPage(mapping, form, request, response);
		return mapping.findForward("listPresent");
	}

	// 编辑
	public ActionForward editPresent(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		String presentID = request.getParameter("presentID");
		String pageNum = request.getParameter("pageNum");

		List<?> shopList = null;
		try {
			shopList = shopService.getAllShop();
		} catch (Exception e) {
			String errorPage = "【物品管理/商品/编辑】查询【商店】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}
		request.setAttribute("shopList", shopList);
		Present present = null;
		try {
			present = presentService.getPresentByPresentID(presentID);
		} catch (Exception e) {
			String errorPage = "【物品管理/商品/编辑】根据【商品ID】查询该【商品】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}
		
		Shop shop = null;
		try {
			shop = shopService.getShopByShopID(present.getShopID());
		} catch (Exception e) {
			String errorPage = "【物资管理/葡萄酒/编辑】根据ID查询该【商店】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}

		request.setAttribute("pageNum", pageNum);
		request.setAttribute("position", "商品/编辑");
		request.setAttribute("shopName", shop.getShopName());
		request.setAttribute("present", present);
		return mapping.findForward("editPresent");
	}

	// 编辑，处理方法
	public ActionForward editPresent_Do(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		String pageNum = request.getParameter("pageNum");

		PresentForm f = (PresentForm) form;
		String presentID = f.getPresentID();
		String presentName = f.getPresentName(); // 商品名称
		String presentType = f.getPresentType(); // 自用 0，送人 1
		String presentState = f.getPresentState(); // 想用 0，在用 1，用完 2
		String presentDate = f.getPresentDate(); // 购买日期，结算时作为流水账的记账日期
		String presentExpenses = f.getPresentExpenses(); // 费用
		String shopID = f.getShopID(); // 商店
		String presentDesc = f.getPresentDesc(); // 描述

		Present present = null;
		try {
			present = presentService.getPresentByPresentID(presentID);
		} catch (Exception e) {
			String errorPage = "【物品管理/商品/编辑】根据【商品ID】查询该【商品】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}
		present.setPresentName(presentName);
		present.setPresentType(presentType);
		present.setPresentState(presentState);
		present.setPresentDate(presentDate);
		present.setPresentExpenses(accountUtil.if1ZeroTo2Zero(presentExpenses));
		present.setShopID(shopID);
		present.setPresentDesc(presentDesc);
		try {
			presentService.saveOrUpdatePresent(present);
		} catch (Exception e) {
			String errorPage = "【物品管理/商品/编辑】保存或更新【商品】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}

		request.setAttribute("pageNum", pageNum);
		listPresentByPage(mapping, form, request, response);
		return mapping.findForward("listPresent");
	}

	// 删除
	public ActionForward delPresent(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		String pageNum = request.getParameter("pageNum");
		Present present = null;
		PresentForm f = (PresentForm) form;
		String[] ids = f.getIds();
		for (int i = 0; i < ids.length; i++) {
			try {
				present = presentService.getPresentByPresentID(ids[i]);
			} catch (Exception e) {
				String errorPage = "【物品管理/商品/删除】根据【商品ID】查询该【商品】异常！" + e.toString();
				log.info(errorPage);
				request.setAttribute("errorPage", errorPage);
				request.setAttribute("position", "出错了");
				return mapping.findForward("errorPage");
			}
			try {
				presentService.deletePresent(present);
			} catch (Exception e) {
				String errorPage = "【物品管理/商品/删除】删除【商品】异常！" + e.toString();
				log.info(errorPage);
				request.setAttribute("errorPage", errorPage);
				request.setAttribute("position", "出错了");
				return mapping.findForward("errorPage");
			}
		}

		request.setAttribute("pageNum", pageNum);
		listPresentByPage(mapping, form, request, response);
		return mapping.findForward("listPresent");
	}

	// 结算
	public ActionForward payPresent(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String presentID = request.getParameter("presentID");
		String pageNum = request.getParameter("pageNum");
		Present present = new Present();
		try {
			present = presentService.getPresentByPresentID(presentID);
		} catch (Exception e) {
			String errorPage = "【物品管理/商品/结算】根据【商品ID】查询该【商品】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}
		// 生成记账凭证
		accountUtil.payExpenseToAccount(present.getPresentDate(), "0030011", "1", present.getPresentExpenses(), "购买",
				present.getPresentName());

		// 更新结算状态，结算完成为"0"
		present.setPresentPay("0");
		try {
			presentService.saveOrUpdatePresent(present);
		} catch (Exception e) {
			String errorPage = "【物品管理/商品/结算】保存或更新【商品】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}

		request.setAttribute("pageNum", pageNum);
		listPresentByPage(mapping, form, request, response);
		return mapping.findForward("listPresent");
	}

	// 明细
	public ActionForward detailPresent(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		String presentID = request.getParameter("presentID");

		Present present = new Present();
		try {
			present = presentService.getPresentByPresentID(presentID);
		} catch (Exception e) {
			String errorPage = "【物品管理/商品/结算】根据【商品ID】查询该【商品】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}
		request.setAttribute("position", "商品/明细");
		request.setAttribute("present", present);
		return mapping.findForward("detailPresent");
	}

	// 分页显示
	public ActionForward listPresentByPage(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		int PAGESIZE = 20;// 每页记录数
		int totalPage = 1;// 总页数

		// 查询总用户记录数
		int count = 0;
		try {
			count = presentService.getCountOfPresentByCondition("");
		} catch (Exception e) {
			String errorPage = "【物品管理/商品】查询【商品】数目异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}
		request.setAttribute("count", count);
		if (count % PAGESIZE == 0) {
			totalPage = count / PAGESIZE;
		} else {
			totalPage = count / PAGESIZE + 1;
		}

		request.setAttribute("totalPage", totalPage);
		// 声明要翻的页
		String pageNum = "1";
		try {
			String thisPageNum = request.getParameter("pageNum");
			// 如果传了页码参数
			if (thisPageNum != null && thisPageNum.length() != 0) {
				pageNum = thisPageNum;
			}
		} catch (RuntimeException e) {
			log.info("" + e.toString());
		}
		log.info("page:" + pageNum);
		request.setAttribute("pageNum", pageNum);
		List<Present> presentList = null;
		List<Present> presentListTemp = new ArrayList<Present>();
		try {
			presentList = presentService.getAllPresentByConditionByPage(" order by presentDate desc",
					Integer.parseInt(pageNum), PAGESIZE);
			for(Present present : presentList) {
				Shop shop = new Shop();
				try {
					shop = shopService.getShopByShopID(present.getShopID());
				} catch (Exception e) {
					String errorPage = "【物资管理/葡萄酒/分页显示】根据商店ID查询【商店】异常！" + e.toString();
					log.info(errorPage);
				}
				present.setShopName(shop.getShopName());
				presentListTemp.add(present);
			}
		} catch (Exception e) {
			String errorPage = "【物品管理/商品】查询【商品】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}
		request.setAttribute("presentList", presentListTemp);
		request.setAttribute("PAGESIZE", PAGESIZE);
		// 如果要翻的这页是第一页
		if ("1".equals(pageNum)) {
			// 设置noUp为yes(界面上用此控制'首页'与'上一页'按钮失效)
			request.setAttribute("noUp", "yes");
		}

		// 如果要翻的这页是最后页
		if (totalPage == Integer.parseInt(pageNum)) {
			// 设置noDown为yes(界面上用此控制'下一页'与'尾页'按钮失效)
			request.setAttribute("noDown", "yes");
		}

		request.setAttribute("action", "present.do");
		request.setAttribute("position", "物资管理/商品");
		return mapping.findForward("listPresent");
	}

	// 数据分析，饼图，柱状图
	public ActionForward barChart(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		request.setAttribute("position", "商品/数据分析");
		return mapping.findForward("datasetPresent");
	}

	// 更改商品状态：已读、未读；在藏、丢失
	public ActionForward statePresent(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String presentID = request.getParameter("presentID");
		String state = request.getParameter("state");
		String pageNum = request.getParameter("pageNum");
		Present present = new Present();
		try {
			present = presentService.getPresentByPresentID(presentID);
		} catch (Exception e) {
			String errorPage = "【物品管理/商品/状态】根据【商品ID】查询该【商品】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}
		if ("songren".equals(state)) {// 送人
			present.setPresentType("1");
		} else if ("ziyong".equals(state)) {// 自用
			present.setPresentType("0");
		} else if ("yiyong".equals(state)) {// 已用
			present.setPresentState("1");
		} else if ("weiyong".equals(state)) {// 未用
			present.setPresentState("0");
		} else {
			log.error("输入参数应为“ziyong”，“yongwan”，“songren”，“weiyong”。");
		}

		try {
			presentService.saveOrUpdatePresent(present);
		} catch (Exception e) {
			String errorPage = "【物品管理/商品/状态】保存或更新【商品】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}

		request.setAttribute("pageNum", pageNum);
		listPresentByPage(mapping, form, request, response);
		return mapping.findForward("listPresent");
	}

	// 查询
	public ActionForward queryPresent(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		request.setAttribute("position", "商品/查询");
		return mapping.findForward("queryPresent");
	}

	// 查询
	public ActionForward queryPresent_Do(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		String sql = request.getParameter("sql");
		PresentForm f = (PresentForm) form;
		String presentName = f.getPresentName(); // 商品名称

		StringBuffer hql = new StringBuffer();
		if (!"".equals(presentName)) {
			hql.append(" where presentName like '%" + presentName + "%'");
		}

		log.info("*******************************************************************" + hql.toString());
		request.setAttribute("tosql", hql.toString());
		int PAGESIZE = 10;// 每页记录数
		int totalPage = 1;// 总页数

		String condition = null;
		if ("".equals(sql) || null == sql) {
			condition = hql.toString();
		} else {
			condition = sql;
		}

		// 查询总用户记录数
		int count = 0;
		try {
			count = presentService.getCountOfPresentByCondition(condition);
		} catch (Exception e) {
			String errorPage = "【物品管理/商品】查询【商品】数目异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}
		request.setAttribute("count", count);
		if (count % PAGESIZE == 0) {
			totalPage = count / PAGESIZE;
		} else {
			totalPage = count / PAGESIZE + 1;
		}

		request.setAttribute("totalPage", totalPage);
		// 声明要翻的页
		String pageNum = "1";
		try {
			String thisPageNum = request.getParameter("pageNum");
			// 如果传了页码参数
			if (thisPageNum != null && thisPageNum.length() != 0) {
				pageNum = thisPageNum;
			}
		} catch (RuntimeException e) {
			log.info("" + e.toString());
		}
		log.info("page:" + pageNum);
		request.setAttribute("pageNum", pageNum);
		List<Present> all = null;
		try {
			all = presentService.getAllPresentByCondition(condition);
		} catch (Exception e) {
			String errorPage = "【物品管理/商品】查询【商品】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}
		request.setAttribute("presentList", all);
		request.setAttribute("presentName", presentName);

		request.setAttribute("position", "商品/查询");
		return mapping.findForward("queryPresent");
	}

	// 商品数据分析，预加载
	public ActionForward listPresentAnalyseJump(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		return mapping.findForward("listPresentAnalyseJump");
	}

	// 商品数据分析
	public ActionForward listPresentAnalyse(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		List<PresentMonth> presentMonthList = null;
		try {
			presentMonthList = presentUtil.getPresentOfTwelveMonths();
		} catch (Exception e) {
			String errorPage = "【物资管理/商品】【最近十二个月的购买商品支出汇总】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}
		request.setAttribute("presentMonthList", presentMonthList);

		List<PresentMonth> presentMonthList2 = null;
		try {
			presentMonthList2 = presentUtil.getPresentOfLastFiveYear();
		} catch (Exception e) {
			String errorPage = "【物资管理/商品】【最近5年商品/网购支出情况汇总】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}
		request.setAttribute("presentMonthList2", presentMonthList2);

		request.setAttribute("position", "商品/数据分析");
		return mapping.findForward("listPresentAnalyse");
	}

	// 查询所有商品
	public ActionForward listPresentByYearAndMonth(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		String ym = request.getParameter("ym");
		String year = "";
		String month = "";
		if (!ym.equals(null) || ym != "") {
			year = ym.substring(0, 4);
			month = ym.substring(4, 6);
		}

		List<Present> presentList = null;
		List<Present> presentListTemp = new ArrayList<Present>();
		try {
			presentList = presentService.getAllPresentByCondition(" where year(presentDate)='" + year
					+ "' and month(presentDate)='" + month + "'");
			for(Present present : presentList) {
				Shop shop = new Shop();
				try {
					shop = shopService.getShopByShopID(present.getShopID());
				} catch (Exception e) {
					String errorPage = "【物资管理/葡萄酒/分页显示】根据商店ID查询【商店】异常！" + e.toString();
					log.info(errorPage);
				}
				present.setShopName(shop.getShopName());
				presentListTemp.add(present);
			}
		} catch (Exception e) {
			String errorPage = "【物品管理/商品】查询【商品】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}

		request.setAttribute("presentList", presentListTemp);
		request.setAttribute("position", "物资管理/商品/网购");
		request.setAttribute("error", "<B>" + ym + "</B>共<B>" + presentList.size() + "</B>条记录");
		return mapping.findForward("listPresentByYearAndMonth");
	}

}